﻿using AutoMapper;
using IOA.MES.DataAccess.Entity;
using IOA.MES.DataAccess.Enum;
using IOA.MES.DataAccess.VModel;
using IOA.MES.Common;
using System;
using System.Collections.Generic;
using System.Linq;

namespace IOA.MES.Business
{
    /// <summary>
    /// 角色管理（错误代码：10701）
    /// </summary>
    public class RoleMgr
    {
        private MESContext mesDb = new MESContext("MES");

        /// <summary>
        /// 查询角色列表
        /// </summary>
        /// <param name="pageIndex">页面索引</param>
        /// <param name="pageSize">页面容量</param>
        /// <param name="total">角色数量</param>
        /// <param name="departmentId">部门ID</param>
        /// <param name="roleName">角色名称</param>
        /// <returns>角色列表</returns>
        public List<VRole> QueryRoles(int pageIndex, int pageSize, out int total, List<int> departmentIds, string roleName)
        {
            if (!departmentIds.Any())
            {
                total = 0;
                return new List<VRole>();
            }
            var query = mesDb.Roles.Where(_ => _.PkId > 1 && departmentIds.Contains(_.DepartmentId) && _.Valid);
            if (!string.IsNullOrWhiteSpace(roleName))
            {
                query = query.Where(_ => _.RoleName.Contains(roleName));
            }

            total = query.Count();

            query = query.OrderBy(_ => _.DepartmentId).ThenBy(_ => _.PkId);
            var entities = pageSize <= 0 ? query.ToList() : query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            var models = Mapper.Map<List<VRole>>(entities);
            var departments = new DepartmentMgr().QueryDepartments();
            models.ForEach(role =>
            {
                var departmentNames = new List<string>();
                var parentId = role.DepartmentId;
                while (true)
                {
                    var curDepartment = departments.FirstOrDefault(_ => _.PkId == parentId);
                    if (curDepartment == null)
                    {
                        break;
                    }
                    parentId = curDepartment.ParentId;
                    departmentNames.Add(curDepartment.DepartmentName);
                }
                departmentNames.Reverse();
                role.DepartmentName = string.Join(">", departmentNames);
            });
            return models;
        }

        /// <summary>
        /// 查询管理角色列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>角色列表</returns>
        public List<VRole> QueryUserManageRoles(int userId)
        {
            var userRoles = (from userRole in mesDb.UserRoles.AsNoTracking().Where(_ => _.UserId == userId && _.Valid)
                             join role in mesDb.Roles.AsNoTracking().Where(_ => _.Valid) on userRole.RoleId equals role.PkId
                             select role).ToList();
            if (!userRoles.Any(_ => _.IsManager))
            {
                return new List<VRole>();
            }

            var userDepartments = new DepartmentMgr().QueryUserDepartments(userId);
            var departmentIds = userDepartments.Select(_ => _.PkId).ToList();
            var roles = mesDb.Roles.AsNoTracking().Where(_ => _.PkId != 1 && departmentIds.Contains(_.DepartmentId) && _.Valid).ToList();

            return Mapper.Map<List<VRole>>(roles);
        }

        /// <summary>
        /// 获取角色对象
        /// </summary>
        /// <param name="roleId">角色ID</param>
        /// <returns>角色对象</returns>
        public VRole GetRole(int roleId)
        {
            var entity = mesDb.Roles.FirstOrDefault(_ => _.PkId == roleId && _.Valid);
            return Mapper.Map<VRole>(entity);
        }

        /// <summary>
        /// 编辑角色
        /// </summary>
        /// <param name="model">角色对象</param>
        public void EditRole(VRole model)
        {
            if (model.PkId <= 0)
            {
                var exist = mesDb.Roles.AsNoTracking().FirstOrDefault(_ => _.RoleName == model.RoleName && _.Valid);
                if (exist != null)
                {
                    throw new MultiLanBizException(10701);// "角色名称已存在，请更换其他名称");
                }

                var departmentRoles = mesDb.Roles.AsNoTracking().Where(_ => _.DepartmentId == model.DepartmentId && _.Valid).ToList();
                if (!departmentRoles.Any())
                {
                    model.IsManager = true;
                }
                model.CreateTime = DateTime.Now;
                model.ModifyBy = 0;
                var entity = Mapper.Map<Role>(model);
                mesDb.Roles.Add(entity);
            }
            else
            {
                var exist = mesDb.Roles.AsNoTracking().FirstOrDefault(_ => _.RoleName == model.RoleName && _.PkId != model.PkId && _.Valid);
                if (exist != null)
                {
                    throw new MultiLanBizException(10701);// "角色名称已存在，请更换其他名称");
                }
                var entity = mesDb.Roles.FirstOrDefault(_ => _.PkId == model.PkId && _.Valid);
                if (entity == null)
                {
                    throw new MultiLanBizException(10702);// "角色不存在或已被删除，无法编辑");
                }
                entity.RoleName = model.RoleName;
                entity.DepartmentId = model.DepartmentId;
                entity.ModifyBy = model.ModifyBy;
                entity.ModifyTime = DateTime.Now;
            }
            mesDb.SaveChanges();
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="model">角色对象</param>
        public void DeleteRole(VRole model)
        {
            var entity = mesDb.Roles.AsNoTracking().FirstOrDefault(_ => _.PkId == model.PkId && _.Valid);
            if (entity == null)
            {
                throw new MultiLanBizException(10703);// "角色不存在或已被删除，无法再次删除");
            }
            var users = (from user in mesDb.Users.AsNoTracking().Where(_ => _.Valid)
                         join userRole in mesDb.UserRoles.AsNoTracking() on user.PkId equals userRole.UserId
                         where user.Valid && userRole.RoleId == model.PkId && userRole.Valid
                         select user).ToList();
            if (users.Any())
            {
                throw new MultiLanBizException(10704, string.Join("、", users.Select(_ => _.TrueName).Distinct()));// $"该角色下还有用户未转移，请先修改这些用户到新的角色，再来删除当前角色，这些用户是：{string.Join("、", users.Select(_ => _.TrueName).Distinct())}");
            }

            mesDb.Roles.Attach(entity);
            entity.Valid = false;
            entity.ModifyBy = model.ModifyBy;
            entity.ModifyTime = DateTime.Now;
            mesDb.SaveChanges();
        }
    }
}
